package org.btik.redstone.led.conf;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Objects;
import java.util.Properties;

/**
 * @author lustre
 * @since 2022/11/29 0:16
 */
public class Conf {
    private static final String PATH = "/light-mc.properties";
    Properties properties;


    private String getProp(String key, String def) {
        Object o = properties.get(key);
        if (o == null) {
            return def;
        }
        return String.valueOf(o);
    }

    private int getProp(String key, int def) {
        Object o = properties.get(key);
        if (o == null) {
            return def;
        }
        return Integer.parseInt(o.toString());
    }

    private final String host;
    private final int port;
    private final int localPort;

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public int getLocalPort() {
        return localPort;
    }


    public Conf(File dir) throws IOException {
        File file = new File(dir, PATH);
        if (!file.exists()) {
            Files.copy(Objects.requireNonNull(getClass().getResourceAsStream(PATH)), file.toPath());
        }
        properties = new Properties();
        try {
            properties.load(new FileInputStream(file));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        this.host = getProp("light.server.host", null);
        this.port = getProp("light.server.nbi.port", 8008);
        this.localPort = getProp("light.mc.nbi.client.port", 233333);
    }

    @Override
    public String toString() {
        return "light server conf:{" +
                "host='" + host + '\'' +
                ", port=" + port +
                ", localPort=" + localPort +
                '}';
    }
}
